package net.pluce.nxt.network.sample;
import java.io.DataOutputStream;
import java.io.FileOutputStream;

import net.pluce.nxt.network.DirectionMessage;
import net.pluce.nxt.network.DistanceMessage;
import net.pluce.nxt.network.RobotConnection;
import net.pluce.nxt.network.RobotConnectionException;
import net.pluce.nxt.network.RobotConnectionFactory;
import net.pluce.nxt.network.RobotListener;
import net.pluce.nxt.network.impl.ThreeIntEventWatcher;

/**
 * Basic use sample of NxtNAL library. Just launch and see comments.
 * <br>It create a fake data file and use the mock implementation of RobotConnection to emulate a robot sending datas over bluetooth.
 * <br>It is its own RobotListener, writing to sysout some text about received informations
 * @author Pluce
 */
public class BasicSample implements RobotListener{

	public BasicSample(){
		
		////////
		// Prepare the mock file
		////////
		try {
			int[] datas = { 1, 24, 345, 2, 90, 2, 1, 45, 456, 2, -90, 2 };
			DataOutputStream dos = new DataOutputStream(new FileOutputStream("fake"));
			for(int i : datas) dos.writeInt(i);
			dos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		/////////
		// End of preparation
		////////
		
		////////
		// Now we start working
		///////
		
		RobotConnection rc = null;
		try {
			// Create a connection
			rc = RobotConnectionFactory.createMockConnection("fake", new ThreeIntEventWatcher());
			////////
			// ThreeIntEventWatcher is the EventWatcher implementation that is used for the actual work in Java
			///////
			
			// Add itself as a listener of the connection
			rc.addListener(this);
			
			// Open the connection
			rc.open();			
		} catch (RobotConnectionException e) {
			// Do whatever you want with exception
			e.printStackTrace();
		}
		finally {
			if(rc != null)
				try {
					// Finally close the connection
					rc.close();
				} catch (RobotConnectionException e) {
					// Do whatever you want with exception
					e.printStackTrace();
				}
		}
	}
	
	public static void main(String[] args) {
		new BasicSample();
	}

	@Override
	public void distanceReceived(DistanceMessage received) {
		// Just print a message !
		System.out.println("distance traveled : " + received.getDistance());
		
	}

	@Override
	public void directionReceived(DirectionMessage received) {
		// Just print a message !
		System.out.println("degrees turned : " + received.getDirection());
		
	}

}
